<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import { invoke } from "@tauri-apps/api/core";

const router = useRouter();

// 公司接口定义 - 匹配后端结构
interface Company {
    id: number;
    name: string;
    type_id: number; // 公司类型: 1-材料生产单位，2-供应商，3-其他服务型
    status: number; // 公司状态: 1-正常，2-停业，3-注销
    address: string;
    contacts: string[];
    staff_num: number; // 员工数量
    capacity: string; // 能够生产什么材料
    remark: string;
    created_by: string;
    modified_by: string;
    created_at: string;
    modified_at: string;
}

// 分页接口定义
interface Pagination<T> {
    page_size: number;
    page_total: number;
    page_current: number;
    page_items: T[];
}

// API响应接口
interface ApiResponse<T> {
    status_code: number;
    error_code: number;
    message: string;
    data: T | null;
}

// 响应式数据
const companies = ref<Company[]>([]);
const loading = ref(false);
const error = ref("");

// 分页相关数据
const pagination = ref<Pagination<Company>>({
    page_size: 10,
    page_total: 0,
    page_current: 1,
    page_items: [],
});

// 搜索参数
const searchParams = ref({
    name: "",
    type_id: "",
    status: "",
});

// 公司类型选项
const companyTypes = [
    { value: "", label: "全部类型" },
    { value: 1, label: "材料生产单位" },
    { value: 2, label: "供应商" },
    { value: 3, label: "其他服务型" },
];

// 公司状态选项
const companyStatuses = [
    { value: "", label: "全部状态" },
    { value: 1, label: "正常" },
    { value: 2, label: "停业" },
    { value: 3, label: "注销" },
];

// 获取公司类型标签
function getCompanyTypeLabel(typeId: number): string {
    const typeObj = companyTypes.find((t) => t.value === typeId);
    return typeObj ? typeObj.label : "未知类型";
}

// 获取公司状态标签和样式
function getCompanyStatusInfo(status: number) {
    const statusObj = companyStatuses.find((s) => s.value === status);
    if (!statusObj) return { label: "未知状态", badgeClass: "badge-neutral" };

    const badgeClasses = {
        1: "badge-success", // 正常 - 绿色
        2: "badge-warning", // 停业 - 黄色
        3: "badge-error", // 注销 - 红色
    };

    return {
        label: statusObj.label,
        badgeClass:
            badgeClasses[status as keyof typeof badgeClasses] ||
            "badge-neutral",
    };
}

// 获取主要联系人
function getPrimaryContact(contacts: string[]): string {
    if (!contacts || contacts.length === 0) return "无联系人";
    return contacts[0].split(",")[0] || contacts[0]; // 取第一个联系人的姓名部分
}

// 从API加载公司数据（支持分页和搜索）
async function loadCompanies(page: number = 1) {
    loading.value = true;
    error.value = "";

    try {
        // 准备查询参数
        const params: any = {
            page_current: page,
            page_size: pagination.value.page_size,
        };

        // 添加搜索条件 - 修复：确保空字符串不会被发送
        if (searchParams.value.name && searchParams.value.name.trim() !== "") {
            params.name = searchParams.value.name;
        }
        if (searchParams.value.type_id && searchParams.value.type_id !== "") {
            params.type_id = parseInt(searchParams.value.type_id);
        }
        if (searchParams.value.status && searchParams.value.status !== "") {
            params.status = parseInt(searchParams.value.status);
        }

        console.log("调用 list_company 参数:", params);

        const response: ApiResponse<Pagination<Company>> = await invoke(
            "list_company",
            params,
        );

        if (response.status_code === 200 && response.data) {
            pagination.value = response.data;
            companies.value = response.data.page_items;
            console.log("获取公司数据成功:", response.data);
        } else {
            error.value = response.message || "获取公司列表失败";
            companies.value = [];
            pagination.value.page_items = [];
            console.error("获取公司数据失败:", response);
        }
    } catch (err) {
        error.value = "网络请求失败，请检查连接";
        console.error("获取公司列表失败:", err);
        companies.value = [];
        pagination.value.page_items = [];
    } finally {
        loading.value = false;
    }
}

// 刷新数据（重置到第一页）
async function refreshData() {
    pagination.value.page_current = 1;
    await loadCompanies(1);
}

// 搜索数据（重置到第一页）
async function searchCompanies() {
    pagination.value.page_current = 1;
    await loadCompanies(1);
}

// 重置搜索条件
function resetSearch() {
    searchParams.value = {
        name: "",
        type_id: "",
        status: "",
    };
    // 重置后重新加载第一页数据
    pagination.value.page_current = 1;
    loadCompanies(1);
}

// 改变页码
function changePage(page: number) {
    if (page < 1 || page > pagination.value.page_total) return;
    pagination.value.page_current = page;
    loadCompanies(page);
}

// 改变每页大小
function changePageSize(size: number) {
    pagination.value.page_size = size;
    pagination.value.page_current = 1;
    loadCompanies(1);
}

// 生成页码数组（用于分页控件）
const pageNumbers = computed(() => {
    const current = pagination.value.page_current;
    const total = pagination.value.page_total;
    const pages = [];

    // 总是显示第一页
    pages.push(1);

    // 当前页附近的页码
    for (
        let i = Math.max(2, current - 1);
        i <= Math.min(total - 1, current + 1);
        i++
    ) {
        if (i > 1 && i < total) {
            pages.push(i);
        }
    }

    // 总是显示最后一页
    if (total > 1) {
        pages.push(total);
    }

    // 去重并排序
    return [...new Set(pages)].sort((a, b) => a - b);
});

// 路由导航
function editCompany(company: Company) {
    router.push({
        name: "companydetail",
        params: { id: company.id.toString() },
    });
}

function addCompany() {
    router.push({
        name: "companydetail",
        params: { id: "new" },
    });
}

function companyDetail(company: Company) {
    router.push({
        name: "companydetail",
        params: { id: company.id.toString() },
    });
}

// 页面加载时初始化
onMounted(() => {
    loadCompanies(1);
});
</script>

<template>
    <main class="min-h-screen bg-base-100 p-4">
        <div class="max-w-7xl mx-auto">
            <!-- 页面标题 -->
            <div class="flex justify-between items-center mb-6">
                <div>
                    <h1 class="text-2xl font-bold text-base-content">
                        公司管理
                    </h1>
                    <p class="text-sm text-gray-500 mt-1">
                        管理供应商、生产单位和服务商信息
                    </p>
                </div>
                <div class="flex gap-2">
                    <button
                        @click="refreshData"
                        class="btn btn-outline btn-sm"
                        :disabled="loading"
                    >
                        <svg
                            class="w-4 h-4"
                            fill="none"
                            stroke="currentColor"
                            viewBox="0 0 24 24"
                            :class="{ 'animate-spin': loading }"
                        >
                            <path
                                stroke-linecap="round"
                                stroke-linejoin="round"
                                stroke-width="2"
                                d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
                            />
                        </svg>
                        刷新
                    </button>
                    <button @click="addCompany" class="btn btn-primary btn-sm">
                        <svg
                            class="w-4 h-4"
                            fill="none"
                            stroke="currentColor"
                            viewBox="0 0 24 24"
                        >
                            <path
                                stroke-linecap="round"
                                stroke-linejoin="round"
                                stroke-width="2"
                                d="M12 6v6m0 0v6m0-6h6m-6 0H6"
                            />
                        </svg>
                        新增公司
                    </button>
                </div>
            </div>

            <!-- 错误提示 -->
            <div v-if="error" class="alert alert-error mb-6">
                <svg
                    class="w-5 h-5"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                >
                    <path
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        stroke-width="2"
                        d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
                    />
                </svg>
                <span>{{ error }}</span>
                <button @click="loadCompanies(1)" class="btn btn-ghost btn-sm">
                    重试
                </button>
            </div>

            <!-- 搜索区域 -->
            <div class="card bg-base-200 shadow-sm mb-6">
                <div class="card-body">
                    <h2 class="card-title text-lg mb-4">
                        <svg
                            class="w-5 h-5"
                            fill="none"
                            stroke="currentColor"
                            viewBox="0 0 24 24"
                        >
                            <path
                                stroke-linecap="round"
                                stroke-linejoin="round"
                                stroke-width="2"
                                d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
                            />
                        </svg>
                        搜索条件
                    </h2>
                    <div
                        class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 items-end"
                    >
                        <!-- 公司名称搜索 -->
                        <div class="form-control">
                            <label class="label">
                                <span class="label-text font-medium"
                                    >公司名称</span
                                >
                            </label>
                            <input
                                v-model="searchParams.name"
                                type="text"
                                placeholder="输入公司名称..."
                                class="input input-bordered"
                                @keyup.enter="searchCompanies"
                            />
                        </div>

                        <!-- 公司类型筛选 -->
                        <div class="form-control">
                            <label class="label">
                                <span class="label-text font-medium"
                                    >公司类型</span
                                >
                            </label>
                            <select
                                v-model="searchParams.type_id"
                                class="select select-bordered"
                                @change="searchCompanies"
                            >
                                <option value="">全部类型</option>
                                <option
                                    v-for="type in companyTypes"
                                    :key="type.value"
                                    :value="type.value"
                                >
                                    {{ type.label }}
                                </option>
                            </select>
                        </div>

                        <!-- 状态筛选 -->
                        <div class="form-control">
                            <label class="label">
                                <span class="label-text font-medium">状态</span>
                            </label>
                            <select
                                v-model="searchParams.status"
                                class="select select-bordered"
                                @change="searchCompanies"
                            >
                                <option value="">全部状态</option>
                                <option
                                    v-for="status in companyStatuses"
                                    :key="status.value"
                                    :value="status.value"
                                >
                                    {{ status.label }}
                                </option>
                            </select>
                        </div>

                        <!-- 操作按钮 -->
                        <div class="form-control">
                            <div class="flex gap-2 mt-2">
                                <button
                                    @click="resetSearch"
                                    class="btn btn-outline flex-1"
                                    :disabled="loading"
                                >
                                    重置
                                </button>
                                <button
                                    @click="searchCompanies"
                                    class="btn btn-primary flex-1"
                                    :disabled="loading"
                                >
                                    <span
                                        v-if="loading"
                                        class="loading loading-spinner loading-sm"
                                    ></span>
                                    搜索
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 加载状态 -->
            <div v-if="loading" class="text-center p-8">
                <span
                    class="loading loading-spinner loading-lg text-primary"
                ></span>
                <p class="mt-2 text-gray-600">加载公司数据中...</p>
            </div>

            <!-- 公司列表 -->
            <div v-else class="card bg-base-100 shadow-sm">
                <div class="card-body p-0">
                    <!-- 列表头部信息 -->
                    <div class="p-4 border-b border-base-300">
                        <div class="flex justify-between items-center">
                            <div>
                                <h2 class="text-lg font-semibold">公司列表</h2>
                                <p class="text-sm text-gray-500 mt-1">
                                    共 {{ pagination.page_total }} 页，
                                    {{ pagination.page_items.length }} 条记录
                                    <span class="ml-2">
                                        每页
                                        <select
                                            :value="pagination.page_size"
                                            @change="
                                                changePageSize(
                                                    parseInt(
                                                        (
                                                            $event.target as HTMLSelectElement
                                                        ).value,
                                                    ),
                                                )
                                            "
                                            class="select select-bordered select-xs mx-1"
                                        >
                                            <option value="10">10</option>
                                            <option value="20">20</option>
                                            <option value="50">50</option>
                                            <option value="100">100</option>
                                        </select>
                                        条
                                    </span>
                                </p>
                            </div>
                            <div
                                class="flex items-center gap-2 text-sm text-gray-500"
                            >
                                <div class="badge badge-success badge-sm"></div>
                                <span>正常</span>
                                <div class="badge badge-warning badge-sm"></div>
                                <span>停业</span>
                                <div class="badge badge-error badge-sm"></div>
                                <span>注销</span>
                            </div>
                        </div>
                    </div>

                    <!-- 表格 -->
                    <div class="overflow-x-auto">
                        <table class="table table-zebra w-full">
                            <thead>
                                <tr class="bg-base-200">
                                    <th class="w-16">ID</th>
                                    <th>公司名称</th>
                                    <th class="w-32">类型</th>
                                    <th class="w-28">主要联系人</th>
                                    <th class="w-38">员工数量</th>
                                    <th class="w-24">状态</th>
                                    <th class="w-28">操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr
                                    v-for="company in pagination.page_items"
                                    :key="company.id"
                                    class="hover cursor-pointer transition-colors duration-200"
                                    @dblclick="companyDetail(company)"
                                >
                                    <td class="font-mono text-sm text-center">
                                        {{ company.id }}
                                    </td>
                                    <td>
                                        <div class="flex flex-col">
                                            <span
                                                class="font-medium text-base"
                                                >{{ company.name }}</span
                                            >
                                            <div
                                                class="flex items-center gap-1 mt-1"
                                            >
                                                <svg
                                                    class="w-3 h-3 text-gray-400"
                                                    fill="none"
                                                    stroke="currentColor"
                                                    viewBox="0 0 24 24"
                                                >
                                                    <path
                                                        stroke-linecap="round"
                                                        stroke-linejoin="round"
                                                        stroke-width="2"
                                                        d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"
                                                    />
                                                    <path
                                                        stroke-linecap="round"
                                                        stroke-linejoin="round"
                                                        stroke-width="2"
                                                        d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"
                                                    />
                                                </svg>
                                                <span
                                                    class="text-xs text-gray-500 truncate max-w-xs"
                                                >
                                                    {{ company.address }}
                                                </span>
                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        <span
                                            class="badge badge-outline badge-sm"
                                        >
                                            {{
                                                getCompanyTypeLabel(
                                                    company.type_id,
                                                )
                                            }}
                                        </span>
                                    </td>
                                    <td>
                                        <span class="text-sm">{{
                                            getPrimaryContact(company.contacts)
                                        }}</span>
                                    </td>
                                    <td>
                                        <div class="flex items-center gap-1">
                                            <svg
                                                class="w-4 h-4 text-gray-400"
                                                fill="none"
                                                stroke="currentColor"
                                                viewBox="0 0 24 24"
                                            >
                                                <path
                                                    stroke-linecap="round"
                                                    stroke-linejoin="round"
                                                    stroke-width="2"
                                                    d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197m13.5-9a2.5 2.5 0 11-5 0 2.5 2.5 0 015 0z"
                                                />
                                            </svg>
                                            <span class="font-mono text-sm"
                                                >{{
                                                    company.staff_num
                                                }}
                                                人</span
                                            >
                                        </div>
                                    </td>
                                    <td>
                                        <span
                                            :class="[
                                                'badge badge-sm',
                                                getCompanyStatusInfo(
                                                    company.status,
                                                ).badgeClass,
                                            ]"
                                        >
                                            {{
                                                getCompanyStatusInfo(
                                                    company.status,
                                                ).label
                                            }}
                                        </span>
                                    </td>
                                    <td>
                                        <div class="flex gap-1">
                                            <button
                                                class="btn btn-ghost btn-sm btn-circle tooltip"
                                                @click.stop="
                                                    companyDetail(company)
                                                "
                                                data-tip="查看详情"
                                            >
                                                <svg
                                                    class="w-4 h-4"
                                                    fill="none"
                                                    stroke="currentColor"
                                                    viewBox="0 0 24 24"
                                                >
                                                    <path
                                                        stroke-linecap="round"
                                                        stroke-linejoin="round"
                                                        stroke-width="2"
                                                        d="M2.036 12.322a1.012 1.012 0 0 1 0-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178Z"
                                                    />
                                                    <path
                                                        stroke-linecap="round"
                                                        stroke-linejoin="round"
                                                        stroke-width="2"
                                                        d="M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z"
                                                    />
                                                </svg>
                                            </button>
                                            <button
                                                class="btn btn-ghost btn-sm btn-circle tooltip"
                                                @click.stop="
                                                    editCompany(company)
                                                "
                                                data-tip="编辑公司"
                                            >
                                                <svg
                                                    class="w-4 h-4"
                                                    fill="none"
                                                    stroke="currentColor"
                                                    viewBox="0 0 24 24"
                                                >
                                                    <path
                                                        stroke-linecap="round"
                                                        stroke-linejoin="round"
                                                        stroke-width="2"
                                                        d="m14.304 4.844 2.852 2.852M7 7H4a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h11a1 1 0 0 0 1-1v-4.5m2.409-9.91a2.017 2.017 0 0 1 0 2.853l-6.844 6.844L8 14l.713-3.565 6.844-6.844a2.015 2.015 0 0 1 2.852 0Z"
                                                    />
                                                </svg>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                    <!-- 空状态 -->
                    <div
                        v-if="pagination.page_items.length === 0 && !loading"
                        class="text-center p-8"
                    >
                        <svg
                            class="w-16 h-16 mx-auto text-gray-400"
                            fill="none"
                            stroke="currentColor"
                            viewBox="0 0 24 24"
                        >
                            <path
                                stroke-linecap="round"
                                stroke-linejoin="round"
                                stroke-width="2"
                                d="M19 21V5a2 2 0 0 0-2-2H7a2 2 0 0 0-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1v5m-4 0h4"
                            />
                        </svg>
                        <p class="mt-4 text-gray-500">暂无公司数据</p>
                        <div class="mt-4 flex gap-2 justify-center">
                            <button
                                @click="resetSearch"
                                class="btn btn-outline btn-sm"
                            >
                                清除搜索条件
                            </button>
                            <button
                                @click="addCompany"
                                class="btn btn-primary btn-sm"
                            >
                                添加第一家公司
                            </button>
                        </div>
                    </div>

                    <!-- 分页控件 -->
                    <div
                        v-if="pagination.page_total > 1"
                        class="p-4 border-t border-base-300"
                    >
                        <div class="flex justify-between items-center">
                            <span class="text-sm text-gray-500">
                                第 {{ pagination.page_current }} 页，共
                                {{ pagination.page_total }} 页， 每页
                                {{ pagination.page_items.length }} 条记录
                            </span>
                            <div class="join">
                                <!-- 上一页 -->
                                <button
                                    class="join-item btn btn-sm"
                                    :disabled="pagination.page_current <= 1"
                                    @click="
                                        changePage(pagination.page_current - 1)
                                    "
                                >
                                    «
                                </button>

                                <!-- 页码按钮 -->
                                <button
                                    v-for="page in pageNumbers"
                                    :key="page"
                                    class="join-item btn btn-sm"
                                    :class="{
                                        'btn-active':
                                            page === pagination.page_current,
                                    }"
                                    @click="changePage(page)"
                                >
                                    {{ page }}
                                </button>

                                <!-- 下一页 -->
                                <button
                                    class="join-item btn btn-sm"
                                    :disabled="
                                        pagination.page_current >=
                                        pagination.page_total
                                    "
                                    @click="
                                        changePage(pagination.page_current + 1)
                                    "
                                >
                                    »
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>
</template>

<style scoped>
/* 确保表格在小屏幕上也能正常显示 */
@media (max-width: 768px) {
    .table {
        font-size: 0.875rem;
    }

    .badge {
        font-size: 0.75rem;
    }

    .join .btn {
        padding-left: 0.5rem;
        padding-right: 0.5rem;
        min-height: 2rem;
        height: 2rem;
    }
}

/* 确保搜索表单元素对齐 */
.form-control {
    display: flex;
    flex-direction: column;
}

.label {
    padding: 0;
    margin-bottom: 0.5rem;
}

.label-text {
    font-weight: 500;
    color: #374151;
}

/* 确保搜索区域网格对齐 */
.grid.items-end {
    align-items: end;
}

/* 分页控件样式优化 */
.join .btn {
    min-width: 2.5rem;
}
</style>
